package emd24.telstudyresources;

import java.util.Iterator;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
 * This class represents the Activity where the user can look over all 
 * the questions he or she answered and has the option to either review
 * or submit answers.
 * 
 * @author Evan Dyke
 *
 */
public class ReviewActivity extends Activity {

	public static final byte A = 65;
	private TextView timerText;
	private Quiz quiz;
	private boolean timed;
	private CountDownTimer time;
	private long millisRemaining;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_review);
		Bundle b = null;
		// Checks to see if there was a previously saved state
		if(savedInstanceState != null){
			b = savedInstanceState;
		}else{
			b = this.getIntent().getExtras();
		}
		this.quiz = b.getParcelable("quiz");
		this.timed = b.getBoolean("timed");
		Long duration = 0L;
		if(this.timed){
			duration = b.getLong("time");
		}
		setTitle("Custom Quiz - " + this.quiz.getName());
		this.timerText = (TextView) this.findViewById(R.id.timerText);
		this.timerText.setTextSize(18);
		if(!this.timed){
			this.timerText.setText("");
		}
		ListView v = (ListView) this.findViewById(R.id.reviewList);
		v.setAdapter(new ReviewAdapter(this, this.quiz.toArray()));
		v.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {
				selectQuestionAt(pos);
			}

		});

		// Set button listeners
		this.findViewById(R.id.revAll).setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				review(false);			
			}
		});
		this.findViewById(R.id.revMark).setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				if(anyMarked()){
					review(true);		
				}
				else{
					noMarkDialog();
				}
			}
		});

		this.findViewById(R.id.Submit).setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				submitDialog();			
			}
		});

		// Set the timer
		if(this.timed){
			this.time = new CountDownTimer(duration, 1000){

				@Override
				public void onFinish() {
					timeFinishedDialog();
				}

				@Override
				public void onTick(long msUntilFinished) {
					// Format the time for the TextView in H:MM:SS
					millisRemaining = msUntilFinished;
					long hours = msUntilFinished / (1000 * 3600);
					long minutes = msUntilFinished / (1000 * 60) % 60;
					long seconds = (msUntilFinished / 1000) % 60;
					timerText.setText("Time Left: " + hours + ":" + ((minutes < 10) ? "0" : "") +  minutes + ":" + 
							((seconds < 10) ? "0" : "") +  seconds);			
				}

			}.start();
		}
	}
	@Override
	protected void onDestroy(){
		if(this.timed){
			this.time.cancel();
		}
		super.onDestroy();
	}
	@Override
	protected void onSaveInstanceState(Bundle outState){
		outState.putParcelable("quiz", this.quiz);
		outState.putBoolean("timed", this.timed);
		outState.putLong("time", this.millisRemaining);
		super.onSaveInstanceState(outState);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_review, menu);
		return true;
	}
	/**
	 * Overrides the back button so a dialog box can be displayed
	 * 
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			backKeyExit();
		}
		return super.onKeyDown(keyCode, event);
	}
	/**
	 * Calls a dialog box before the test is submitted. 
	 * 
	 */
	private void submitDialog(){
		new AlertDialog.Builder(this).setMessage(R.string.submit_final).
		setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			// Set listener for when yes button is clicked, exit activity
			public void onClick(DialogInterface arg0, int arg1) {
				results();
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {

			// Set listener for no button
			public void onClick(DialogInterface arg0, int arg1) {
			}
		}).show();
	}
	private void noMarkDialog(){
		new AlertDialog.Builder(this).setMessage(R.string.no_marked).
		setNeutralButton("Ok", new DialogInterface.OnClickListener() {

			// Set listener for when yes button is clicked, exit activity
			public void onClick(DialogInterface arg0, int arg1) {

			}
		}).show();
	}
	/**
	 * Displays a dialog and finishes the quiz. THis is tp be called when
	 * the timer is done counting down.
	 * 
	 */
	private void timeFinishedDialog(){
		new AlertDialog.Builder(this).setMessage("Time's up!").setCancelable(false).
		setNeutralButton("Continue", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				results();
			}


		}).show();
	}
	/**
	 * Calls the QuestionActivity to go through the quiz
	 * a second time to review.
	 * 
	 * @param mark boolean whether to view only marked questions 
	 * 
	 */
	private void review(boolean mark){
		Intent review = new Intent(this,QuestionActivity.class);
		review.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		review.putExtra("quiz",this.quiz);
		if(this.timed){
			review.putExtra("timed", true);
			review.putExtra("time", this.millisRemaining);
		}else{
			review.putExtra("timed", false);
		}
		if(mark){
			review.putExtra("mark", true);
			review.putExtra("qIndex", this.quiz.getNextMarked(-1));
		}else{
			review.putExtra("mark", false);
			review.putExtra("qIndex", 0);
		}
		startActivity(review);
		finish();
	}
	/**
	 * Starts the questionActivity at a given index
	 * 
	 * @param pos
	 */
	private void selectQuestionAt(int pos){
		Intent question = new Intent(this,QuestionActivity.class);
		question.putExtra("quiz",this.quiz);
		if(this.timed){
			question.putExtra("timed", true);
			question.putExtra("time", this.millisRemaining);
		}else{
			question.putExtra("timed", false);
		}
		question.putExtra("mark", false);
		question.putExtra("qIndex", pos);
		startActivity(question);
		finish();
	}
	/**
	 * Calls the results screen.
	 * 
	 */
	private void results(){
		Intent results = new Intent(this,ResultsActivity.class);
		results.putExtra("quiz", this.quiz);
		startActivity(results);
		finish();
	}
	/**
	 * Displays a dialog box asking the user if they are sure
	 * they want to exit the quiz. If the user selects yes, the
	 * activity is finished.
	 * 
	 */
	private void backKeyExit(){
		new AlertDialog.Builder(this).setMessage(R.string.quiz_exit).
		setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			// Set listener for when yes button is clicked, exit activity
			public void onClick(DialogInterface arg0, int arg1) {
				finish();
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {

			// Set listener for no button
			public void onClick(DialogInterface arg0, int arg1) {
			}
		}).show();

	}
	/**
	 * Checks to see is there are any marked questions in the quiz
	 * 
	 * @return boolean whether any marked questions exist
	 */
	private boolean anyMarked(){
		Iterator<Question> iter = this.quiz.iterator();
		while(iter.hasNext()){
			if(iter.next().isMarked()){
				return true;
			}
		}
		return false;
	}
	/**
	 * This is an adapter for the ListView for StudyMode. It populates
	 * data with questions
	 * 
	 * @author Evan Dyke
	 *
	 */
	private class ReviewAdapter extends BaseAdapter {

		private Question[] questions;
		private ReviewAdapter(Context c, Question[] questions){
			this.questions = questions;
			LayoutInflater.from(c);
		}

		@Override
		public int getCount() {
			return this.questions.length;
		}

		@Override
		public Object getItem(int position) {
			return this.questions[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView qNumber;
			TextView qAnswer;
			TextView qMarked;
			if(convertView == null){
				LayoutInflater inflater = LayoutInflater.from(parent.getContext());
				convertView = inflater.inflate(R.layout.review_row_view, parent, false);

			} 
			qNumber = (TextView) convertView.findViewById(R.id.qNumber);
			qAnswer = (TextView) convertView.findViewById(R.id.qAnswer);
			qMarked = (TextView) convertView.findViewById(R.id.qMarked);

			qNumber.setText("Q" + this.questions[position].getQuestionNumber());
			if(this.questions[position].getSelectedAnswer() == -1){
				qAnswer.setText("You answered: Nothing");
			}else{
				qAnswer.setText("You answered: " + Character.toString((char) (this.questions[position].getSelectedAnswer() + A)));
			}

			// Indicate whether the question is marked
			if(this.questions[position].isMarked()){
				qMarked.setTextColor(Color.GREEN);
				qMarked.setText("Marked");
			}
			else{
				qMarked.setTextColor(Color.BLACK);
				qMarked.setText("");
			}
			return convertView;
		}

	}

}
